package com.cloud.jvm.ref;

import java.util.HashMap;
import java.util.WeakHashMap;

/**
 * @version v1.0
 * @author: TianXiang
 * @description: 弱引用- 将对象包装了一层
 * @date: 2021/5/31
 */
public class WeakRef {

    public static void main(String[] args) {

//        Object o1 = new Object();
//        WeakReference<Object> weakRef = new WeakReference<>(o1);
//        System.out.println(o1);// java.lang.Object@2957fcb0
//        System.out.println(weakRef.get());// java.lang.Object@2957fcb0
//
//        o1 = null;
//        System.gc();
//        System.out.println("==========================================================");
//
//        System.out.println(o1);// null
//        System.out.println(weakRef.get());// null

        myHashMap();
        System.out.println("==========================================================");
        weakHashMap();
    }


    public static void weakHashMap() {
        WeakHashMap<Integer, String> map = new WeakHashMap<>();
        Integer k = new Integer(1);
        String v = "value";

        map.put(k, v);
        System.out.println(map);// {1=value}

        k = null;
        System.out.println(map);// {1=value}

        System.gc();
        System.out.println(map);// {} 只要GC就会回收key
    }

    public static void myHashMap() {
        HashMap<Integer, String> map = new HashMap<>();
        Integer k = new Integer(1);
        String v = "value";

        map.put(k, v);
        System.out.println(map);// {1=value}

        // hashMap里的key都是新创建的Node 所以k=null 不会影响到Map里的key
        k = null;
        System.out.println(map);// {1=value}

        System.gc();
        System.out.println(map);// {1=value}
    }

}
